package com.zenrs.ui

import kotlinx.cinterop.*
import platform.posix.*

// 错误码定义
external fun zenrs_zig_init(): Boolean

external fun zenrs_zig_allocate(size: ULong): COpaquePointer?
external fun zenrs_zig_free(ptr: COpaquePointer?, size: ULong): Unit

// 从Rust服务层导入的函数
external fun zenrs_kotlin_interop_init(): Boolean
external fun zenrs_send_ui_command(
    command: CPointer<KotlinUICommand>,
    result_code: CPointer<IntVar>
): Boolean
external fun zenrs_register_ui_event_callback(
    callback: (CPointer<KotlinUIEvent>) -> Unit,
    user_data: COpaquePointer?
): Boolean

external fun zenrs_get_system_info(
    buffer: CPointer<ByteVar>,
    buffer_size: UInt,
    actual_size: CPointer<UIntVar>
): Boolean

external fun zenrs_allocate_memory(size: ULong, out_ptr: CPointer<CPointerVar<COpaquePointer>>): Boolean
external fun zenrs_free_memory(ptr: COpaquePointer?): Boolean

external fun zenrs_create_shared_memory(
    size: ULong,
    name: CPointer<Int8Var>,
    out_handle: CPointer<ULongVar>
): Boolean
external fun zenrs_open_shared_memory(
    handle: ULong,
    out_ptr: CPointer<CPointerVar<COpaquePointer>>,
    out_size: CPointer<ULongVar>
): Boolean
external fun zenrs_close_shared_memory(handle: ULong): Boolean

external fun zenrs_send_custom_message(
    target_id: ULong,
    message_type: UInt,
    data: CPointer<ByteVar>,
    data_size: UInt
): Boolean

external fun zenrs_get_application_list(
    buffer: CPointer<ByteVar>,
    buffer_size: UInt,
    actual_size: CPointer<UIntVar>
): Boolean

external fun zenrs_launch_application(app_id: ULong, result_code: CPointer<IntVar>): Boolean
external fun zenrs_close_application(app_id: ULong, result_code: CPointer<IntVar>): Boolean

// 从Zig内核层导入的函数
external fun zenrs_zig_create_ui_channel(
    name: CPointer<Int8Var>,
    cap_id: ULong,
    out_channel_id: CPointer<ULongVar>
): Int
external fun zenrs_zig_send_ui_message(
    channel_id: ULong,
    message_type: UInt,
    sender_id: ULong,
    target_id: ULong,
    data: CPointer<ByteVar>,
    data_size: ULong
): Int
external fun zenrs_zig_get_system_status(
    buffer: CPointer<ByteVar>,
    buffer_size: ULong,
    out_actual_size: CPointer<ULongVar>
): Int
external fun zenrs_zig_create_kuikly_channel(
    name: CPointer<Int8Var>,
    cap_id: ULong,
    out_channel_id: CPointer<ULongVar>
): Int
external fun zenrs_zig_close_ui_channel(channel_id: ULong): Int
external fun zenrs_zig_get_channel_stats(
    channel_id: ULong,
    out_message_count: CPointer<UIntVar>,
    out_used_memory: CPointer<ULongVar>
): Int
external fun zenrs_zig_convert_kuikly_message(
    channel_id: ULong,
    kuikly_msg: CPointer<ByteVar>,
    msg_size: ULong,
    out_message_id: CPointer<ULongVar>
): Int
external fun zenrs_zig_set_ui_property(
    component_id: ULong,
    property_name: CPointer<Int8Var>,
    property_value: CPointer<ByteVar>,
    value_size: ULong
): Int
external fun zenrs_zig_get_ui_property(
    component_id: ULong,
    property_name: CPointer<Int8Var>,
    buffer: CPointer<ByteVar>,
    buffer_size: ULong,
    out_actual_size: CPointer<ULongVar>
): Int
external fun zenrs_zig_create_shared_memory(
    size: ULong,
    name: CPointer<Int8Var>,
    out_handle: CPointer<ULongVar>
): Int
external fun zenrs_zig_open_shared_memory(
    handle: ULong,
    out_ptr: CPointer<CPointerVar<ByteVar>>,
    out_size: CPointer<ULongVar>
): Int
external fun zenrs_zig_close_shared_memory(handle: ULong): Int

// 数据结构定义
@CStruct
data class KotlinUIEvent(
    var event_type: UInt,
    var x: Int,
    var y: Int,
    var button_state: UInt,
    var key_code: UInt,
    var modifier_state: UInt,
    var timestamp: ULong
)

@CStruct
data class KotlinUICommand(
    var command_id: UInt,
    var target_id: ULong,
    var data_size: UInt,
    var data_ptr: CPointer<ByteVar>?
)

// 错误码常量
const val ZENRS_ERROR_NONE = 0
const val ZENRS_ERROR_INVALID_PARAM = 1
const val ZENRS_ERROR_NO_MEMORY = 2
const val ZENRS_ERROR_NOT_INITIALIZED = 3
const val ZENRS_ERROR_NOT_SUPPORTED = 4

// 消息类型常量
const val UI_EVENT_MOUSEMOVE = 1u
const val UI_EVENT_MOUSEDOWN = 2u
const val UI_EVENT_MOUSEUP = 3u
const val UI_EVENT_KEYDOWN = 4u
const val UI_EVENT_KEYUP = 5u
const val UI_EVENT_RESIZE = 6u
const val UI_EVENT_FOCUS = 7u
const val UI_EVENT_BLUR = 8u

// UI命令常量
const val UI_COMMAND_CREATE_WINDOW = 1001u
const val UI_COMMAND_DESTROY_WINDOW = 1002u
const val UI_COMMAND_UPDATE_VIEW = 1003u
const val UI_COMMAND_SET_PROPERTY = 1004u
const val UI_COMMAND_REQUEST_FOCUS = 1005u
const val UI_COMMAND_RELEASE_FOCUS = 1006u

// Kotlin/Native与Rust、Zig互操作的帮助类
object ZenrsFFIHelper {
    // 初始化FFI接口
    fun initialize(): Boolean {
        // 初始化Zig FFI
        val zigInitResult = zenrs_zig_init()
        println("Zig FFI initialization: $zigInitResult")
        
        // 初始化Rust FFI
        val rustInitResult = zenrs_kotlin_interop_init()
        println("Rust FFI initialization: $rustInitResult")
        
        return zigInitResult && rustInitResult
    }
    
    // 分配内存
    fun allocateMemory(size: ULong): COpaquePointer? {
        return zenrs_zig_allocate(size)
    }
    
    // 释放内存
    fun freeMemory(ptr: COpaquePointer?, size: ULong) {
        zenrs_zig_free(ptr, size)
    }
    
    // 发送UI命令
    fun sendUICommand(commandId: UInt, targetId: ULong, data: ByteArray? = null): Boolean {
        return memScoped {
            val resultCode = alloc<IntVar>()
            resultCode.value = 0
            
            val command = alloc<KotlinUICommand>()
            command.command_id = commandId
            command.target_id = targetId
            
            if (data != null) {
                val dataPtr = data.toCValues().ptr
                command.data_size = data.size.toUInt()
                command.data_ptr = dataPtr
            } else {
                command.data_size = 0u
                command.data_ptr = null
            }
            
            val result = zenrs_send_ui_command(command.ptr, resultCode.ptr)
            println("Send UI command result: $result, code: ${resultCode.value}")
            result
        }
    }
    
    // 创建UI通信通道
    fun createUIChannel(name: String, capId: ULong): ULong {
        return memScoped {
            val channelId = alloc<ULongVar>()
            channelId.value = 0u
            
            val cName = name.cstr
            val result = zenrs_zig_create_ui_channel(cName, capId, channelId.ptr)
            
            if (result == ZENRS_ERROR_NONE) {
                println("UI channel created with ID: ${channelId.value}")
                channelId.value
            } else {
                println("Failed to create UI channel, error code: $result")
                0u
            }
        }
    }
    
    // 发送UI消息
    fun sendUIMessage(
        channelId: ULong,
        messageType: UInt,
        senderId: ULong,
        targetId: ULong,
        data: ByteArray? = null
    ): Boolean {
        return memScoped {
            val dataPtr: CPointer<ByteVar>?
            val dataSize: ULong
            
            if (data != null) {
                dataPtr = data.toCValues().ptr
                dataSize = data.size.toULong()
            } else {
                dataPtr = null
                dataSize = 0u
            }
            
            val result = zenrs_zig_send_ui_message(
                channelId, messageType, senderId, targetId, dataPtr, dataSize
            )
            
            val success = (result == ZENRS_ERROR_NONE)
            println("Send UI message result: $success")
            success
        }
    }
    
    // 获取系统信息
    fun getSystemInfo(): String {
        return memScoped {
            // 首先获取需要的缓冲区大小
            val actualSize = alloc<ULongVar>()
            actualSize.value = 0u
            
            // 第一次调用获取大小
            zenrs_zig_get_system_status(null, 0u, actualSize.ptr)
            
            if (actualSize.value > 0u) {
                // 分配足够大的缓冲区
                val buffer = ByteArray(actualSize.value.toInt())
                buffer.usePinned {
                    val result = zenrs_zig_get_system_status(
                        it.addressOf(0), actualSize.value, actualSize.ptr
                    )
                    
                    if (result == ZENRS_ERROR_NONE) {
                        // 转换为字符串
                        return@memScoped String(buffer)
                    }
                }
            }
            
            // 如果出错，返回空字符串
            return@memScoped ""
        }
    }
    
    // 创建Kuikly专用通道
    fun createKuiklyChannel(name: String, capId: ULong): ULong {
        return memScoped {
            val channelId = alloc<ULongVar>()
            channelId.value = 0u
            
            val cName = name.cstr
            val result = zenrs_zig_create_kuikly_channel(cName, capId, channelId.ptr)
            
            if (result == ZENRS_ERROR_NONE) {
                println("Kuikly channel created with ID: ${channelId.value}")
                channelId.value
            } else {
                println("Failed to create Kuikly channel, error code: $result")
                0u
            }
        }
    }
    
    // 获取应用列表
    fun getApplicationList(): String {
        return memScoped {
            // 首先获取需要的缓冲区大小
            val actualSize = alloc<UIntVar>()
            actualSize.value = 0u
            
            // 第一次调用获取大小
            zenrs_get_application_list(null, 0u, actualSize.ptr)
            
            if (actualSize.value > 0u) {
                // 分配足够大的缓冲区
                val buffer = ByteArray(actualSize.value.toInt())
                buffer.usePinned {
                    val result = zenrs_get_application_list(
                        it.addressOf(0), actualSize.value, actualSize.ptr
                    )
                    
                    if (result) {
                        // 转换为字符串
                        return@memScoped String(buffer)
                    }
                }
            }
            
            // 如果出错，返回空字符串
            return@memScoped ""
        }
    }
    
    // 启动应用
    fun launchApplication(appId: ULong): Boolean {
        return memScoped {
            val resultCode = alloc<IntVar>()
            resultCode.value = 0
            
            val result = zenrs_launch_application(appId, resultCode.ptr)
            println("Launch application result: $result, code: ${resultCode.value}")
            result
        }
    }
    
    // 关闭应用
    fun closeApplication(appId: ULong): Boolean {
        return memScoped {
            val resultCode = alloc<IntVar>()
            resultCode.value = 0
            
            val result = zenrs_close_application(appId, resultCode.ptr)
            println("Close application result: $result, code: ${resultCode.value}")
            result
        }
    }
    
    // 创建共享内存
    fun createSharedMemory(size: ULong, name: String): ULong {
        return memScoped {
            val handle = alloc<ULongVar>()
            handle.value = 0u
            
            val cName = name.cstr
            val result = zenrs_zig_create_shared_memory(size, cName, handle.ptr)
            
            if (result == ZENRS_ERROR_NONE) {
                println("Shared memory created with handle: ${handle.value}")
                handle.value
            } else {
                println("Failed to create shared memory, error code: $result")
                0u
            }
        }
    }
    
    // 设置UI组件属性
    fun setUIProperty(componentId: ULong, propertyName: String, propertyValue: String): Boolean {
        return memScoped {
            val cName = propertyName.cstr
            val cValue = propertyValue.cstr
            
            val result = zenrs_zig_set_ui_property(
                componentId, cName, cValue, propertyValue.length.toULong()
            )
            
            val success = (result == ZENRS_ERROR_NONE)
            println("Set UI property result: $success")
            success
        }
    }
    
    // 获取UI组件属性
    fun getUIProperty(componentId: ULong, propertyName: String): String {
        return memScoped {
            // 首先获取需要的缓冲区大小
            val actualSize = alloc<ULongVar>()
            actualSize.value = 0u
            
            val cName = propertyName.cstr
            
            // 第一次调用获取大小
            zenrs_zig_get_ui_property(
                componentId, cName, null, 0u, actualSize.ptr
            )
            
            if (actualSize.value > 0u) {
                // 分配足够大的缓冲区
                val buffer = ByteArray(actualSize.value.toInt())
                buffer.usePinned {
                    val result = zenrs_zig_get_ui_property(
                        componentId, cName, it.addressOf(0), actualSize.value, actualSize.ptr
                    )
                    
                    if (result == ZENRS_ERROR_NONE) {
                        // 转换为字符串
                        return@memScoped String(buffer)
                    }
                }
            }
            
            // 如果出错，返回空字符串
            return@memScoped ""
        }
    }
}